﻿using JwtAuthSample.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Security;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Extensions.Options;
using System.Text;
using System.IdentityModel.Tokens.Jwt;

namespace JwtAuthSample.Controllers
{
    [Route("api/[controller]")]
    public class AuthorizeController : Controller
    {
        private readonly JwtSettings jwtSettings;
        public AuthorizeController(IOptions<JwtSettings> options)
        {
            jwtSettings = options.Value;
        }
        [HttpPost("Token")]
        public IActionResult Token([FromBody]LoginViewModel view)
        {
            if (!ModelState.IsValid) return BadRequest();

            if (!(view.User == "dp" && view.PassWord == "123456")) return BadRequest();
            var claims = new Claim[]
            {
                new Claim(ClaimTypes.Name,"dp"),
                new Claim(ClaimTypes.Role,"admin"),
                new Claim("SuperAdminOnly", "true")
        };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecreKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(jwtSettings.Issurer, jwtSettings.Audience, claims, DateTime.Now,
                DateTime.Now.AddMinutes(30), creds);

            return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
        }
    }
}
